package guicommon.controls;

import guicommon.gui.WindowMessage;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.JWindow;

public class Window extends Control{

    private final int
            arcWidth = 10,
            arcHeight = 10,
            systemButtonSize = 16,
            systemButtonSizeWithOffset = 18;

    private static Image hide, window, close;

    private Button closeButton;

    private String title;

    private JWindow windowComponent;

    public void SetTitle(String title) {
        this.title = title;
    }

    public String GetTitle() {
        return title;
    }

    public Window() {
        super();
        hide = LoadImage("hide_button.png");
        window = LoadImage("window_button.png");
        close = LoadImage("close_button.png");
        windowComponent = new JWindow();
        closeButton = new Button();
        closeButton.SetSize(systemButtonSize, systemButtonSize);
        closeButton.SetPoint(-systemButtonSizeWithOffset * 2 - arcWidth / 2, - systemButtonSize - arcHeight / 2);
    }

    @Override
    public WindowMessage ToMessage() {
        WindowMessage result = new WindowMessage();
        SetCommonFields(result);
        result.SetTitle(title);
        return result;
    }

    public Graphics GetGraphics() {
        if (image == null) {
           image = new BufferedImage(GetWidth() - arcWidth, GetHeight() - 7 * arcHeight / 2, BufferedImage.TYPE_4BYTE_ABGR);
        }
        return image.getGraphics();
    }

    public int GetXOffset() {
        return arcWidth / 2;
    }

    public int GetYOffset() {
        return 3 * arcHeight;
    }

    @Override
    public void Draw(Graphics g, JPanel board) {
        g.setColor(Color.blue);
        int x = GetX(), y = GetY(), width = GetWidth(), height = GetHeight();
        g.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
        g.setColor(GetBackGround());
        g.fill3DRect(x + arcWidth / 2, y + 3 * arcHeight, width - arcWidth, height - 7 * arcHeight / 2, true);
        image.flush();
        g.drawImage(image, x + GetXOffset(), y + GetYOffset(), board);

        g.setColor(Color.WHITE);
        g.drawString(title, x + arcWidth, y + 3 * arcHeight / 2);

        int localX = x + width - systemButtonSizeWithOffset * 4, localY = y + arcHeight / 2;
        g.drawImage(hide, localX, localY, board);
        localX += systemButtonSizeWithOffset;
        g.drawImage(window, localX, localY, board);
        localX += systemButtonSizeWithOffset;
        g.drawImage(close, localX, localY, board);        
    }

    @Override
    public boolean IsContainer() {
        return true;
    }

    protected Component GetComponent() {
        return windowComponent;
    }

    public Button GetCloseButton() {
        return closeButton;
    }
}
